<template>
  <div class="form-layout">
    <!--左侧导航-->
    <div class="nav-left">
      <customAnchor
        :itemList="[
          { name: 'box-base', title: '清点信息' },
          { name: 'box-dtl', title: '清点明细' },
        ]"
      />
    </div>

    <!--表单区域-->
    <div class="form-right" ref="formRight">
      <customForm :data="form" :rules="propRules" ref="editForm" :disabled="propReadonly">
        <template #content>
          <div id="box-base" class="box-title">清点信息</div>
          <customFormItem
            label="备货单" name="prepareKey" :parent="_self" :form="form"
            :readonly="true" :showSelectIcon="true"
            @focus="$refs.tableDrawerPrepare.show()"
            :disabled="!propParent.cpFormNew"
            help="保存后不可修改"
          />

          <customFormItem
            label="科室" name="deptName" :parent="_self" :form="form"
            :readonly="true" :showSelectIcon="true" @focus="utilSelect.dept(deptIdChange)"
            :disabled="!propParent.cpFormNew"
            help="保存后不可修改"
          />

          <customFormItem label="仓库" name="warehouseName" :parent="_self" :form="form"
                          :readonly="true" :showSelectIcon="true"
                          @focus="utilSelect.warehouse(warehouseNameChange, form.warehouseId)"
                          :disabled="!propParent.cpFormNew"
                          help="保存后不可修改"
          />

          <customFormItem
            label="清点日期" name="checkDate" :parent="_self" :form="form"
            :type="constCommon.formItemType.datePicker.name"
            disabled
          />

          <customFormItem
            label="清点单号" name="checkKey" :parent="_self" :form="form"
            :type="constCommon.formItemType.staticHtml.name"
            disabled
          />
          <customFormItem
            label="清点人" name="checkPersion2" :parent="_self" :form="form"
            :type="constCommon.formItemType.staticHtml.name"
            disabled
          />

          <customFormItem
            label="手术单号" name="oprtCode" :parent="_self" :form="form"
            v-if="cpIsOprtApplyType1"
            disabled
          />
          <customFormItem
            label="手术日期" name="oprtDate" :parent="_self" :form="form"
            :type="constCommon.formItemType.datePicker.name"
            v-if="cpIsOprtApplyType1"
            disabled
          />
          <customFormItem
            label="患者" name="patientName" :parent="_self" :form="form"
            :readonly="true" :showSelectIcon="true"
            @focus="utilSelect.patient(patientChange)"
            v-if="cpIsOprtApplyType1"
            disabled
          />
          <customFormItem
            label="患者年龄" name="patientAge" :parent="_self" :form="form"  :type="constCommon.formItemType.inputNumber.name"
            v-if="cpIsOprtApplyType1"
            disabled
          />
          <customFormItem
            label="床位号" name="bedNo" :parent="_self" :form="form"
            v-if="cpIsOprtApplyType1"
            disabled
          />
          <customFormItem
            label="住院编号" name="patientNo" :parent="_self" :form="form"
            v-if="cpIsOprtApplyType1"
            disabled
          />
          <customFormItem
            label="主治医生" name="docNameSug" :parent="_self" :form="form"
            v-if="cpIsOprtApplyType1"
            disabled
          />
          <customFormItem
            label="专家" name="docNameApply" :parent="_self" :form="form"
            v-if="cpIsOprtApplyType1"
            disabled
          />
          <customFormItem label="备注" name="remark"  :parent="_self" :form="form" />
        </template>
      </customForm>
      <div id="box-dtl" class="box-title">
        清点明细
        <small class="box-title2">
          <customTooltip title="扫描标签码添加明细">
            <template #title>
              <div>
                <strong>消耗</strong>
                <div style="padding-left: 10px">
                  将产生可消耗库存用于【科室扫码消耗】操作
                </div>
              </div>
              <div>
                <strong>退货</strong>
                <div style="padding-left: 10px">
                  将指定数量的商品进行【供应商退货】操作
                </div>
              </div>
            </template>
            <template #content>
              消耗、退货说明
            </template>
          </customTooltip>
        </small>
      </div>
      <data-view
        propViewKey="wm_oprt_check_item"
        :propInitData="form"
        ref="childDataView"
        :propNoEditRow="true"
        propEditConfigMode="cell"
        :propHideFlowSelect="true"
        :propFlowKey="propParent.propFlowKey"
        :propParentPage="_self"
        :propAutoFetchData="false"
        :propParentData="propParent.viewFormData"
        @edit-input="rowEditInput"
        :propActiveRowMethod="propActiveRowMethod"
        :propBeforeClick="propBeforeClickDtl"
      />
    </div>

    <!--备货申请单选择-->
    <tableDrawer ref="tableDrawerPrepare" refName="tableDrawerPrepare"
       @confirm="tableDrawerPrepareChange" viewKey="wm_oprt_prepare_select"
       subtitle="已审核尚未进行清点的跟台申请单"
    />

    <!--清点结果-->
    <tableDrawer  loadForce attach="body" ref="tableDrawerResult" refName="tableDrawerResult" viewKey="wm_oprt_check_result" :queryWrapper="cpTableDrawerResultQueryWrapper"/>
  </div>
</template>

<script>
import packSelect from '@/components/base/PackSelect.vue'
import customAnchor from '@/components/custom/form/customAnchor.vue'

export default {
  data() {
    return {
      form: {},
      viewData: {},
      formDisabled: false,
      propColumns: [
        { name: 'matrName', title: '耗材名称', width: 250 },
        { name: 'matrSpec', title: '耗材规格', width: 200 },
        { name: 'skuQty', title: '备货数量', width: 100 },
        { name: 'patientQty', title: '消耗数量', width: 150 },
        { name: 'spQty', title: '退货数量', width: 150 },
        { name: 'returnCleanQty', title: '退洁数量', width: 150 },
        { name: 'returnPolluteQty', title: '退污数量', width: 150 },
        { name: 'sn', title: 'SN', width: 200 },
        { name: 'skuPrice', title: '价格', width: 200 },
        { name: 'amount', title: '金额', width: 200 },
        { name: 'supplierName', title: '供应商', width: 200 }

      ],
      propEditColumns: ['patientQty', 'spQty', 'returnCleanQty', 'returnPolluteQty'],
      checkItemId: null
    }
  },
  methods: {
    // 加载明细数据
    fetchChildData() {
      let queryWrapper = this.$newWrapper()
      if (this.form.id) {
        queryWrapper.eq('checkId', this.form.id)
      } else {
        queryWrapper.ne(1, 1)
      }
      this.$refs.childDataView.setQueryWrapper(queryWrapper)
    },
    refreshData() {
      //刷新本页面表单
      this.propParent.ocRefreshCurrentRow()
      //刷新上级网格明细
      this.propParent.ocRefresh()
    },
    deleteMatr() {
      this.utilMessage.warning('对不起，清点耗材不允许删除')
    },
    deletePackage() {
      this.utilMessage.warning('对不起，清点包不允许删除')
    },
    getChildQueryWrapper() {
      if (this.form.id) {
        return this.$newWrapper().eq('checkId', this.form.id).eq('matr_type', '1')
      } else {
        return this.$newWrapper().ne(1, 1)
      }
    },
    childRowEdit({row, column}) {
      const skuQty = Number(row.skuQty)
      const patientQty = Number(row.patientQty)
      let spQty = Number(row.spQty)
      const returnCleanQty = Number(row.returnCleanQty)
      const returnPolluteQty = Number(row.returnPolluteQty)
      if (patientQty < 0 || spQty < 0 || returnCleanQty < 0 || returnPolluteQty < 0) {
        this.utilMessage.warning('数量不能为负数！请检查')
        this.fetchData()
        return
      }
      if ((patientQty + spQty + returnCleanQty + returnPolluteQty) > skuQty) {
        this.utilMessage.warning('消耗数量+退货数量+退洁数量+退污数量不能超过备货数量哦')
        return
      }
      if ((patientQty + spQty + returnCleanQty + returnPolluteQty) < skuQty) {
        this.utilMessage.warning('消耗数量+退货数量+退洁数量+退污数量不能低于备货数量哦')
        return
      }
      if (patientQty + spQty + returnCleanQty + returnPolluteQty === row.skuQty) {
        spQty = skuQty - patientQty - returnCleanQty - returnPolluteQty
        let params = {
          patient_qty: patientQty,
          sp_qty: spQty,
          return_clean_qty: returnCleanQty,
          return_pollute_qty: returnPolluteQty,
          id: row.id
        }
        this.$ajax.post('/wm/oprt_check_item/updateSpQty', params)
          .then((resp) => {
            if (resp.code === 0) {
              this.utilMessage.success('数量已更新！')
            }
          })
      }
    },
    fetchData() {
      this.$refs.childDataView.fetchData()
    },
    async handleChangePrepare() {
      if (!this.form.warehouseId) {
        this.utilMessage.warning('请先选择消毒供应室')
        this.form.prepareId = null
        return
      }
      for (const s1 of this.propDictionaries.prepareId.filter(s => this.form.prepareId == s.id)) {
        this.$set(this.form, 'oprtName', s1.oprtName)
        this.$set(this.form, 'oprtDate', s1.oprtDate)
        this.$set(this.form, 'patientName', s1.patientName)
        this.$set(this.form, 'patientAge', s1.patientAge)
        this.$set(this.form, 'patientNo', s1.patientNo)
        this.$set(this.form, 'bedNo', s1.bedNo)
        this.$set(this.form, 'adocNameSug', s1.adocNameSug)
        this.$set(this.form, 'docNameApply', s1.docNameApply)
        if (!this.form.id && !this.propReadonly) {
          await this.propParent.ocAsynSaveViewForm()
        }
        let params = {
          'checkId': this.form.id,
          'prepareId': s1.id
        }
        this.$ajax.post('/wm/oprt_check_item/addCheckItem', params)
          .then((resp) => {
            this.fetchData()
          })
      }
      this.refreshData()
    },

    // 科室选择
    deptIdChange(item) {
      this.$set(this.form, 'deptId', item.id)
      this.$set(this.form, 'deptName', item.name)
    },

    // 仓库选择
    warehouseNameChange(row) {
      this.$set(this.form, 'warehouseId', row.id)
      this.$set(this.form, 'warehouseName', row.name)
    },

    // 备货单选择
    tableDrawerPrepareChange(row) {
      this.$set(this.form, 'prepareId', row.id)
      this.$set(this.form, 'prepareKey', row.prepareKey)
      this.$set(this.form, 'prepareType', row.prepareType)
      this.$set(this.form, 'oprtId', row.oprtId)
      this.$set(this.form, 'oprtName', row.oprtName)
      this.$set(this.form, 'oprtCode', row.oprtCode)
      this.$set(this.form, 'oprtDate', row.oprtDate)
      this.$set(this.form, 'patientId', row.patientId)
      this.$set(this.form, 'patientName', row.patientName)
      this.$set(this.form, 'patientAge', row.patientAge)
      this.$set(this.form, 'patientNo', row.patientNo)
      this.$set(this.form, 'bedNo', row.bedNo)
      this.$set(this.form, 'docNameSug', row.docNameSug)
      this.$set(this.form, 'docNameApply', row.docNameApply)
    },

    // 行编辑 column.model.value保存了原值
    rowEditInput({row, column}) {
      //消耗、退货、退洁、退污
      if (['patientQty','spQty','returnCleanQty','returnPolluteQty'].includes(column.property)) {
        let sum = row.patientQty + row.spQty + row.returnCleanQty + row.returnPolluteQty
        let diff = row.skuQty - sum
        if (diff < 0) {
          this.utilMessage.warning(`消耗、退货总数量【${sum}】已超过备货数量【${row.skuQty}】, 请检查`)
          this.$set(row, column.property, column.model.value)
        }
      }
    },

    // 杭是否可以编辑
    propActiveRowMethod(column, row) {
      if (this.form.flowStatus != 'submit') {
        return false
      }
      // 当前行，是包模板时，禁用编辑
      if ('1' == row.matrType ) {
        return false
      }
      return true
    },

    // 扩展按钮事件
    propBeforeClickDtl(button, formData , rowData, that) {
      let buttonKey = button.key
      console.log('button', button)
      if (buttonKey === 'resultDtl') { // 明细查看
        this.checkItemId = rowData.id
        this.$refs.tableDrawerResult.show()
      }
    }

  },
  created() {
    let that = this
    this.$emit('event-register', {
      validate: (callback) => {
        return this.$refs.editForm.validate(callback)
      },
      beforeSave: () => {
        this.$emit('data-callback', this.form)
        return true
      },
      afterMove: (formData, initData) => {
        this.form = global.utils.jsonClone(formData)
        let wrapper = this.getChildQueryWrapper()
        if (!this.form.id) {
          this.$set(this.form, 'deptId', this.utils.getCurrentUser().deptId)
          this.$set(this.form, 'deptName', this.utils.getCurrentUser().deptName)

          this.$set(this.form, 'checkDate', new Date().format(this.dates.defaultDatePattern))
          this.$set(this.form, 'checkPersion2', this.utils.getCurrentUser().name)
        }
        this.fetchChildData()
      },
      afterClick: (button) => {
        let buttonKey = button.key
        if (buttonKey === 'resultMain') { // 主表查看
          that.checkItemId = null
          this.$refs.tableDrawerResult.show()
        } else if (buttonKey == 'printLabel') {
          global.utilPrint.openPrintLabel(null, that.form.workOrderKey, null)
        }
      },
      beforeDelete: () => {
        return true
      },
      afterDelete: () => {
      },
      beforeFlow: (flowButtonKey) => {
        return true
      },
      afterFlow: (valueTo) => {
        that.fetchChildData()
      },
      beforeClose: () => {
        return true
      }
    })
  },
  props: {
    propParent: Object,
    propInitData: Object,
    propPrimaryKey: String,
    propDictionaries: Object,
    propCurrentRow: Object,
    propViewFormData: Object,
    propReadonly: Boolean,
    propStatus: String,
    propRules: Object
  },
  components: {packSelect, customAnchor},
  computed: {
    // 是否是手术备货申请
    cpIsOprtApplyType1() {
      return this.form.prepareType == this.constCommon.dictType.oprtApplyTypeOprt
    },
    // 清点查询条件
    cpTableDrawerResultQueryWrapper() {
      let queryWrapper = this.$newWrapper()
      queryWrapper.eq('checkId', this.form.id)
      if (this.strings.isNotBlank(this.checkItemId)) {
        queryWrapper.eq('checkItemId', this.checkItemId)
      }
      return queryWrapper
    }
  }
}
</script>
